package com.cdty.chess.config;

import com.auth0.jwt.JWT;
import com.auth0.jwt.JWTVerifier;
import com.auth0.jwt.algorithms.Algorithm;
import com.auth0.jwt.exceptions.JWTDecodeException;
import com.auth0.jwt.exceptions.JWTVerificationException;
import com.cdty.chess.model.Cuser;
import com.cdty.chess.service.CuserService;
import com.cdty.chess.util.TokenUtils;
import com.google.protobuf.ServiceException;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.HandlerInterceptor;

import java.util.List;


@Component
public class JwtInterceptor implements HandlerInterceptor {
    @Autowired
    private CuserService userService;


    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        // 检查请求是否为 WebSocket 请求
        if (isWebSocketRequest(request)) {
            // 如果是 WebSocket 请求，直接放行
            return true;
        }
        String token = request.getHeader("token");
        if (token != null && token.startsWith("\"") && token.endsWith("\"")) {
            token = token.substring(1, token.length() - 1);
        }
        if(!(handler instanceof HandlerMethod)){
            return true;
        }

        // 执行认证
            if (!StringUtils.hasText(token)) {
                response.setStatus(401);
            throw new ServiceException("无token验证失败");
        }
        // 验证签名
        try {
            JWTVerifier verifier = JWT.require(Algorithm.HMAC256(TokenUtils.SECRET)).build();
            verifier.verify(token);
        } catch (JWTVerificationException e) {
            response.setStatus(401);
            throw new ServiceException("Token 非法");
        }

        // 获取 jti 和用户ID
        String userId = JWT.decode(token).getAudience().get(0);
        String tokenJti = JWT.decode(token).getClaim("jti").asString();

        // 查询数据库中的最新 jti
        Cuser user = new Cuser();
        user.setUid(userId);
        List<Cuser> cuser = userService.getCuser(user);
        if (cuser.size() == 0 || !tokenJti.equals(cuser.get(0).getCurrent_jti())) {
            response.setStatus(401);
            throw new ServiceException("Token 已失效");
        }
        return true;
    }

    private boolean isWebSocketRequest(HttpServletRequest request) {
        // 检查请求协议是否为 WebSocket 协议
        String upgradeHeader = request.getHeader("Upgrade");
        return "websocket".equalsIgnoreCase(upgradeHeader);
    }
}